﻿
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEngine.UI.GridLayoutGroup;

namespace Gameplay.CharacterFramework
{
    public abstract class Weapon:MonoBehaviour
    {
        public WeaponConfig Config;

        protected WeaponManager _weaponManager;

        private BoxCollider _collider;
        private Role _owner;

        [SerializeField] private List<Detection> _detections;
        [SerializeField] private bool _isOnDetection;

        protected virtual void Awake()
        {
            _collider = GetComponent<BoxCollider>();
            if (_collider != null) 
            {
                _collider.enabled = false;
            }
           
        }
        protected virtual void Update() 
        {
            HandleDetection();
        }

        private void HandleDetection()
        {
            if (_isOnDetection) 
            {
                foreach (var item in _detections)
                {
                    foreach (var hit in item.GetDetection())
                    {
                        AttackDetails attackDetails = new AttackDetails();
                        attackDetails.Damage = Config.Damage;
                        attackDetails.Target = _owner;
                        hit.GetComponent<AgentHitBox>().TakeDamage(hit.ClosestPoint(transform.position), attackDetails);
                    }
                }
            }
        }

        public void Init(Role role,WeaponManager weaponManager) 
        {
            _owner = role;
            _weaponManager = weaponManager;
        }
        public void SetActive(bool active) 
        {
            if (_collider != null) 
            {
                _collider.enabled = active;
            }
        }

        public void ToToggleDetection(bool value) 
        {
            _isOnDetection = value;
            if (value)
            {
                HandleDetection();
            }
            else
            {
                foreach(var item in _detections) 
                {
                    item.ClearWasHit();
                }

            }


        }

        protected virtual void OnTriggerEnter(Collider other)
        {
            Role character = other.GetComponent<Role>();
            if (character != null)
            {
                Vector3 closesPoint = other.ClosestPoint(transform.position);
                character.TakeDamage(_owner, _owner.SkillManager.CurrentUseSkill.Config.DamageValue, closesPoint);
            }
        }
    }
}
